<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'

import { Table } from '@/components/Table'
import { spDrugListApi, spDrugAddAdminApi, spDrugEditApi, spDrugDelApi } from '@/api/sp/drug'
import { zcPastureListApi } from '@/api/fa/pasture'
import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive, unref } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const userInfo: any = wsCache.get('userInfo')
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
// const iconFile = useIcon({ icon: 'material-symbols:drive-file-move-sharp' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spDrugListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '牧场名称',
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    },
    search: {
      show: true
    }
  },
  {
    field: 'pasture_org_id',
    label: '牧场名称',
    search: {
      show: false
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: zcPastureListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        relNameField: 'org_name',
        title: '选择标签组（双击选择）',
        nameField: 'pasture_org_name',
        valueField: 'pasture_org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '牧场名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'name',
    label: '药品名称',
    search: {
      show: true
    }
  },
  {
    field: 'total_stock',
    label: '总库存',
    form: {
      show: false
    }
  },
  {
    field: 'available_stock',
    label: '可用库存',
    form: {
      show: false
    }
  },
  {
    field: 'note',
    label: '药品备注'
  },
  {
    field: 'create_user_name',
    label: '创建人',
    form: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: false
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 150,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm(`删除该药品档案？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row.id)
        })
        .catch(() => {})
      break
    default:
  }
}
const del = async (val) => {
  let res = await spDrugDelApi({ id: val })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    getList()
  }
}
const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)
const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          const props = {
            id: data.id,
            admin_org_id: data.admin_org_id,
            admin_dept_id: data.admin_dept_id,
            admin_user_id: data.admin_user_id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            pasture_user_id: data.pasture_user_id,
            name: data.name,
            note: data.note,
            is_del: '0'
          }
          let res = await spDrugEditApi(props)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          const props = {
            my_org_id: userInfo.default_org_id,
            my_dept_id: userInfo.default_dept_id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            pasture_user_id: data.pasture_user_id,
            name: data.name,
            note: data.note
          }
          let res = await spDrugAddAdminApi(props)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'file':
      break
    default:
      console.log('未知类型')
  }
}

const init = async () => {
  await getList()
}
init()
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <!-- :selection="false" -->
      <template #total_stock="{ row }">
        <span>{{ row.total_stock ? row.total_stock : 0 }}</span>
      </template>
      <template #available_stock="{ row }">
        <span>{{ row.total_stock ? row.total_stock : 0 }}</span>
      </template>
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton circle :icon="iconDel" @click="action('del', row)" title="删除" />
        <!-- <ElButton circle :icon="iconFile" @click="action('file', row)" title="确认归档" /> -->
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'add'" ref="editRef" />
    <Edit v-if="actionType == 'edit'" ref="editRef" :current-row="tableObject.currentRow" />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />
    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
